<template>
  <div>
    <el-card class="search-card">
      <basic-table-form
        ref="formData"
        :colNumOfRow="4"
        :formColumns="formItemList"
        :dataSource="formData"
        :defaultExpandStatus="false"
        :handleSearchForm="handleQueryForm"
        @getFormData="getFormData"
      >
      </basic-table-form>
    </el-card>
    <el-card class="table-card">
      <basic-table
        showActionCol
        :loading="tableInfo.loading"
        :columns="tableInfo.columns"
        :dataSource="tableInfo.list"
        :pagination="pagination"
        :tableHeight="460"
        :selection-change="selectionChange"
        :actionRender="renderTableBtnAction"
        @pageChange="handlePageChange"
        @pageSizeChange="handlePageSizeChange"
      >
        <el-row slot="content_context" type="flex" justify="start">
          <BtnRender :render="renderBtnsBar" />
        </el-row>
      </basic-table>
    </el-card>
    <TurnToSendDialog
      :sendVisable.sync="sendVisable"
      :supplierData="supplierData"
      @getTableData="getTableData"
    />
    <RecordDialog
      :recordVisable.sync="recordVisable"
      :supplierData="supplierData"
    />
    <!-- 导出 -->
    <ExportDialog
      :visible.sync="exportVisible"
      :exportInfo='exportInfo'
      :total='pagination.total'
    />
  </div>
</template>
<script>
import BasicTableForm from '@/components/supplier/BasicForm';
import BasicTable from '@/components/supplier/BasicTable';
import ExportDialog from '@supplier/components/ExportDialog';
import TurnToSendDialog from './components/TurnToSendDialog';
import RecordDialog from './components/RecordDialog';
import { FORM_ITEM_LIST, initTableColumns } from './constants';
import { getBtnsId } from '@/libs/btnsPermission';
import BasicPage from '@/mixins/supplier/basicPage';
import Dict from '@/mixins/supplier/dict';
import {
  queryToInspectSupplierService,
  exportToInspectSupplierService
} from '@api/supplier/returnVisteManage';
import BtnRender from '@/components/JSXRender/BtnRender';
import { getBtnsBar, getTableAction } from '@supplier/utils/btnsUtils';

export default {
  mixins: [ BasicPage, Dict ], // 分页数据及方法 表单基础方法
  components: {
    BasicTableForm,
    BasicTable,
    TurnToSendDialog,
    RecordDialog,
    BtnRender,
    ExportDialog
  },
  data () {
    return {
      exportVisible: false,
      sendVisable: false,
      recordVisable: false,
      supplierData: {}, // 转派
      batchPushDownLoading: false,
      formItemList: FORM_ITEM_LIST,
      tableInfo: {
        list: [],
        selection: [],
        columns: initTableColumns(this),
        loading: false
      },
      formData: {
        supplierCode: '',
        supplierName: '',
        supplierClassify: '',
        mainCategoryId: '',
        managementAreaId: '',
        belongDepartment: '',
        businessContact: '',
        inspectionPersonName: '',
        inspectCycle: '',
        inspectionClassify: '',
        inspectionState: '',
        pushTime: [],
        endTime: []
      },
      exportInfo: {}
    };
  },
  created () {
    this.getTableData();
  },
  methods: {
    // 渲染按钮操作栏
    renderBtnsBar (h) {
      const { selection } = this.tableInfo;
      const disabled = selection.length == 0;
      const btnsBar = [
        {
          label: '批量下推考察计划',
          size: 'mini',
          type: 'primary',
          method: () => { this.handlePushDown(selection) },
          disabled,
          hasAuth: true
        },
        {
          label: '转派',
          size: 'mini',
          type: 'primary',
          method: () => { this.handleTurnToSend('send') },
          disabled,
          hasAuth: true
        },
        {
          label: '转派记录',
          size: 'mini',
          type: 'primary',
          method: () => { this.handleTurnToSend('record') },
          disabled,
          hasAuth: true
        },
      ];
      if (this.supplierExportConfig.returnViste) {
        btnsBar.unshift({
          label: '导出',
          method: this.handleExport,
          loading: this.exportLoading,
          size: 'mini',
          type: 'primary',
          hasAuth: true
        })
      }
      return getBtnsBar(h, btnsBar, this.showBtn);
    },
    // 渲染列表操作项
    renderTableBtnAction (h, { row }) {
      const actionList = []
      if (row.inspectionState == 1) {
        actionList.push({ label: '下推考察计划', method: this.handlePushDown, hasAuth: true })
      }
      return getTableAction({ h, row, actionList, showBtn: this.showBtn });
    },
    // 勾选需要处理
    selectionChange (rows) {
      this.tableInfo.selection = rows;
    },
    // 初始化查询条件
    initSearchParams () {
      const { pushTime = [], endTime = [] } = this.formData;
      const [pushTimeStart = '', pushTimeEnd = ''] = pushTime;
      const [endTimeStart = '', endTimeEnd = ''] = endTime;
      return _.omit({
        ...this.formData,
        pushTimeStart,
        pushTimeEnd,
        endTimeStart,
        endTimeEnd
      }, 'pushTime', 'endTime')
    },
    // 获取表格数据
    async getTableData () {
      let data = {
        ...this.initSearchParams(),
        ...this.pagination
      };
      sessionStorage.setItem('buttonId', getBtnsId('查询'));
      this.tableInfo.loading = true;
      const res = await queryToInspectSupplierService(data, state => { this.tableInfo.loading = state })
      if (res) {
        const { records, total } = res.result;
        this.tableInfo.list = records;
        this.pagination.total = total;
      }
    },
    // 下推
    handlePushDown (param, supplierCodes) {
      const userId = localStorage.userInfo ? JSON.parse(localStorage.userInfo).userId : '';
      if (!userId) {
        return this.$message.warning('用户信息获取失败，请重新登录')
      }
      if (Array.isArray(param)) {
        if (param.some(item => item.inspectionState != 1)) {
          return this.$message.warning('只支持下推考察状态为待考察的供应商')
        }
        if (param.some(item => item.inspectionPersonId != userId)) {
          return this.$message.warning('非考察人不可下推考察计划')
        }
        supplierCodes = param.map(item => item.supplierCode)
      } else {
        if (param.inspectionPersonId != userId) {
          return this.$message.warning('非考察人不可下推考察计划')
        }
        supplierCodes = [param.supplierCode];
      }
      this.$confirm('确认将供应商下推考察计划吗？', '下推考察计划', {
        type: 'warning',
      }).then(() => {
        this.$router.push({ name: 'addPlan', query: { supplierCodes } })
      });
    },
    // 导出
    async handleExport () {
      this.exportVisible = true;
      this.exportInfo = {
        service: exportToInspectSupplierService,
        excelTitle: '待考察供应商',
        params: this.initSearchParams(),
      }
    },
    // 转派
    handleTurnToSend (type) {
      if (this.tableInfo.selection.length > 1) {
        return this.$message.warning('暂不支持批量转派')
      }
      const { supplierId, supplierCode, id } = this.tableInfo.selection[0]
      this.supplierData = {
        supplierCode,
        supplierId,
        id
      }
      if (type == 'send') {
        this.sendVisable = true;
      } else {
        this.recordVisable = true;
      }
    }
  }
};
</script>
